package com.lsj.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lsj.core.exception.CustomerException;
import com.lsj.core.page.QueryPage;
import com.lsj.core.page.ResultPage;
import com.lsj.core.response.ResponseType;
import com.lsj.core.util.ExceptionHelperUtil;
import com.lsj.core.util.QueryHelperUtil;
import com.lsj.dto.sys.UserDto;
import com.lsj.dto.sys.UserPwdResetDto;
import com.lsj.dto.sys.UserUpdateDto;
import com.lsj.mapper.SysUserMapper;
import com.lsj.mapper.SysUserRoleMapper;
import com.lsj.mapper.entity.SysUser;
import com.lsj.mapper.entity.SysUserRole;
import com.lsj.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author:lin.sj
 * @Data:2021/7/7 19:46
 * @Desc: 用户信息处理
 */
@Service
public class UserServiceImpl implements UserService  {
    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    PasswordEncoder passwordEncoder;

    /**
     * @Author: lin.sj
     * @Date: 2021/7/7 20:00
     * @Desc: 注册账户
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void register(UserDto userDto) throws CustomerException {
        boolean existsUsername = existsUsername(userDto.getUsername());
        if(existsUsername){
            throw new CustomerException(ResponseType.error,"当前账户已存在！");
        }
        SysUser sysUser = Convert.convert(SysUser.class, userDto);
        //加密插入的密码
        sysUser.setPassword(passwordEncoder.encode(sysUser.getPassword()));
        sysUser.setEnabled(true);
        sysUserMapper.insert(sysUser);
    }
    /**
     * @Author: lin.sj
     * @Date: 2021/7/7 20:10
     * @Desc: 检查是否存在该用户名
     **/
    @Override
    public boolean validateUsername(String username) {
        return existsUsername(username);
    }

    /**
     * @Author: lin.sj
     * @Date: 2021/7/21 22:33
     * @Desc: 更新用户基本信息，但不包括账户和密码
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUser(UserUpdateDto userUpdateDto) {
        SysUser sysUser = getUser(userUpdateDto.getId());
        if(sysUser == null){
            throw new CustomerException(ResponseType.error,"用户信息不存在，无法更新！");
        }
        BeanUtil.copyProperties(userUpdateDto,sysUser);
        sysUserMapper.updateById(sysUser);
    }

    /**
     * @Author: lin.sj
     * @Date: 2021/8/18 20:16
     * @Desc: 根据ID获取用户信息
     **/
    @Override
    public UserDto getUserById(Long id) {
        SysUser sysUser = getUser(id);
        return Convert.convert(UserDto.class,sysUser);
    }

    /**
     * @Author: lin.sj
     * @Date: 2021/8/18 20:16
     * @Desc: 获取用户列表
     **/
    @Override
    public ResultPage<UserDto> listUser(QueryPage<UserDto> queryPage) {
        UserDto userDto = queryPage.getData();
        QueryWrapper<SysUser> w = QueryHelperUtil.getSimpleWhere(SysUser.class, userDto);
        Page page = sysUserMapper.selectPage(queryPage.getMpPage(), w);
        return ResultPage.getResult(page, UserDto.class);
    }

    /**
     * @Author: lin.sj
     * @Date: 2021/8/18 20:16
     * @Desc: 删除用户
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteUserById(long userId) {
        //删除用户与角色关联关系
        LambdaQueryWrapper<SysUserRole> w = QueryHelperUtil.getLambdaWrapper(SysUserRole.class);
        w.eq(SysUserRole::getUserId,userId);
        sysUserRoleMapper.delete(w);
        sysUserMapper.deleteById(userId);
    }

    /**
     * @Author: lin.sj
     * @Date: 2021/7/22 20:30
     * @Desc: 重置用户密码
     **/
    @Override
    public void passwordReset(UserPwdResetDto resetDto) {
        SysUser sysUser = sysUserMapper.selectById(resetDto.getId());
        ExceptionHelperUtil.nullObjException(sysUser,"用户不存在，无法更新密码！");
        sysUser.setPassword(passwordEncoder.encode(resetDto.getPassword()));
        sysUserMapper.updateById(sysUser);
    }

    /**
     * @Author: lin.sj
     * @Date: 2021/8/18 20:16
     * @Desc: 判断当前用户账户是否存在(公用方法)
     **/
    private boolean existsUsername(String username){
        LambdaQueryWrapper<SysUser> w = new LambdaQueryWrapper<>();
        w.eq(SysUser::getUsername,username);
        Integer existsCount = sysUserMapper.selectCount(w);
        return existsCount > 0?true:false;
    }

    /**
     * @Author: lin.sj
     * @Date: 2021/8/18 20:18
     * @Desc: 根据Id获取用户(公用方法)
     **/
    public SysUser getUser(Long id){
        LambdaQueryWrapper<SysUser> w = new LambdaQueryWrapper<>();
        w.eq(SysUser::getId,id);
        SysUser sysUser = sysUserMapper.selectOne(w);
        return sysUser;
    }
}
